package Region.socket;

import Region.DatabaseManager;
import Region.LogManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class RegionToRegionReceiveThread implements Runnable{
    private Socket socket;
    public BufferedReader input = null;
    public PrintWriter output = null;
    private DatabaseManager dataBaseManager;
    private LogManager logManager;
    private String tableName;

    public RegionToRegionReceiveThread(String tableName, Socket socket, DatabaseManager dataBaseManager, LogManager logManager) throws IOException {
        this.socket = socket;
        this.logManager = logManager;
        this.dataBaseManager = dataBaseManager;
        this.tableName = tableName;

        this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.output = new PrintWriter(socket.getOutputStream());
    }

    @Override
    public void run(){
        String sql;
        try {
            System.out.println("开始接收消息");
            output.println(tableName);
            output.flush(); // 确保立即发送tableName

            while (!(sql = input.readLine()).equals("END")) {
                dataBaseManager.updateSQL(sql);
                logManager.addLog(tableName, sql);
            }
            System.out.println("log接收完成");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
